// https://leetcode.cn/problems/fruit-into-baskets/
// Created by ade on 2022/10/17.
//
#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

class Solution {
public:
    // 思路：当m的元素个数大于2时，说明存在溢出，此时不断右移left的位置，直到m的个数等于2，此时就是最大的集合个数，不断比较之
    int totalFruit(vector<int> &fruits) {
        int len = fruits.size();
        unordered_map<int, int> m = {};
        int num = 0, maxI = 0, left = 0;
        for (int i = 0; i < len; i++) {
            m[fruits[i]]++;
            num++;
            if (m.size() > 2) {
                while (m.size() > 2) {
                    m[fruits[left]]--;
                    num--;
                    if (m[fruits[left]] == 0) {
                        m.erase(fruits[left]);
                        left++;
                        break;
                    } else {
                        left++;
                    }
                }
            } else {
                maxI = max(num, maxI);
            }
        }
        maxI = max(num, maxI);
        return maxI;
    }
};

int main() {
    Solution so;
    vector<int> m = {1, 0, 3, 4, 3};
    cout << so.totalFruit(m) << endl;
    return 0;
}